<template>
  <div style="width: 100%;height: 100vh;overflow:hidden ;background-color: darkcyan;">
    <div style="width: 400px;margin: 150px auto">
      <div style="color:#cccccc; padding: 30px 0; font-size: 30px;text-align: center">欢迎注册</div>
      <el-form ref="formRef" :model="form" size="normal" :rules="rules">
        <el-form-item prop="username">
          <el-input placeholder="请输入用户名" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input placeholder="请输入密码" type="password" v-model="form.password" style=""></el-input>
        </el-form-item>
        <el-form-item prop="confirm">
          <el-input placeholder="确认密码" type="password" v-model="form.confirm" style=""></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100%;" @click="register" type="primary">注册</el-button>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100%;" @click="toLogin" type="primary">已有帐号</el-button>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "Register",
  components: {},
  data() {
    return {
      form: {},
      //表单校验规则
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
          },
        ],
        confirm: [
          {
            required: true,
            message: '请确认密码',
            trigger: 'blur',
          },
        ],
      }
    }
  },
  methods: {
    toLogin(){
      this.$router.push("/login")
    },
    register() {
      //判断两次密码是否一致
      if (this.form.password !== this.form.confirm) {
        this.$message({
          type: "error",
          message: "2次密码输入不一致!"
        })
        return
      }

      //满足校验规则才传给后台数据
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          //将登录信息传给后台
          request.post("/user/register", this.form).then(res => {
            if (res.code === '0') {
              this.$message({
                type: "success",
                message: "注册成功"
              })
              this.$router.push("/login") //Register成功后进行页面跳转 跳转到登录
            } else {
              this.$message({
                type: "error",
                message: res.msg
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>